package p

import (
	"gitee.com/tietang/terrace-go/v2/base/starter/iinflux"
	"github.com/influxdata/influxdb-client-go/api"
	"github.com/silenceper/pool"
	log "github.com/sirupsen/logrus"
)

type WriteAPIBlockingPool struct {
	Pool pool.Pool
}

func NewPoolWriteAPIBlocking(config pool.Config) *WriteAPIBlockingPool {
	api := &WriteAPIBlockingPool{}
	config.Close = api.poolClose
	config.Factory = api.poolFactory
	p, err := pool.NewChannelPool(&config)
	if err != nil {
		log.Error(err)
	}
	api.Pool = p
	return api
}
func (s *WriteAPIBlockingPool) Exe(fn func(api.WriteAPIBlocking) error) {
	api := s.Get()
	defer s.Put(api)
	err := fn(api)
	if err != nil {
		log.Error(err)
	}
}
func (s *WriteAPIBlockingPool) poolFactory() (interface{}, error) {
	return iinflux.WriteAPIBlocking(), nil
}
func (s *WriteAPIBlockingPool) poolClose(v interface{}) (err error) {
	return nil
}
func (s *WriteAPIBlockingPool) Get() api.WriteAPIBlocking {
	v, err := s.Pool.Get()
	if err != nil {
		log.Error(err)
	}
	return v.(api.WriteAPIBlocking)
}
func (s *WriteAPIBlockingPool) Put(api api.WriteAPIBlocking) {
	err := s.Pool.Put(api)
	if err != nil {
		log.Error(err)
	}
}

func (s *WriteAPIBlockingPool) Release() {
	s.Pool.Release()
}

func (s *WriteAPIBlockingPool) Len() int {
	return s.Pool.Len()
}
func (s *WriteAPIBlockingPool) Close(api api.WriteAPIBlocking) {
	s.Pool.Close(api)
}
